package com.ks.app.product.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import com.ks.app.product.hibernate.KRoomImage;
import com.ks.app.product.service.KsroomService;
import com.ks.app.search.util.Constants;

public class UploadImage {
	private File upload;
	private File dir;
	private FileOutputStream fos;
	private FileInputStream fis;

	public String doAddPhoPic(KsroomService ksroomServiceimpl, File file,
			String fileName) {
		String str = "";
		// 自己的PhotoService接口处理
		this.upload = file;
		KRoomImage rphoto = new KRoomImage();
		// 这里简单的demo没有要把名字规范，也没有对图片有剪切或缩小处理，所以就简单的把上传的图片以1,2,3命名
		int count = 1;
		count++;
		String file_path = "";
		try {
			 dir = new File(Constants.BASE_ROOT);
			  //判断文件夹是否存在,如果不存在则创建文件夹
				if(!file .exists() && !file .isDirectory()){
					System.out.println("创建文件夹");
					file.mkdirs();
				}else{
					System.out.println("文件夾存在");
				}
			// 上传至该项目所在本地目录
			file_path = Constants.BASE_ROOT + "/" + fileName.substring(0,fileName.lastIndexOf(".")) + ".jpg";
			rphoto.setImageName(fileName);
			rphoto.setImagepath(file_path);
			int tag = ksroomServiceimpl.insertPhoto(rphoto);
			System.out.println("print out the file_path---------" + file_path);
			//存储操作成功才执行对文件的读写操作
			if (tag == 1) {
				// 对文件进行写操作
				fos = new FileOutputStream(file_path);
				// 对文件进行读操作
				fis = new FileInputStream(upload);
				byte[] buffer = new byte[1024];
				int len = 0;
				// 读入流，保存至byte数组
				while ((len = fis.read(buffer)) > 0) {
					fos.write(buffer, 0, len);
				}
				str = "success";
			}else{
				str = "error";
			}

		} catch (Exception e) {
			System.out.println("insert the image get a exception" + e.getMessage());
		} finally {
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (fis != null) {

				try {
					fis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}

			}
		}
		return str;
	}
}